<?php

namespace app\api\service\intelligentlive;

use app\api\model\intelligentlive\Product;
use app\lib\exception\intelligentlive\IntelligentliveException;
use think\Db;
use think\Exception;
use think\Request;

class ProductService
{
    private static $instance;

    public static function getInstance(): ProductService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function addProduct($params)
    {
        $product = Product::where("product_id",$params['product_id'])->findOrEmpty();
        if (!$product->isEmpty()){
            throw new intelligentliveException([
                'msg' => "该商品已存在，请勿重复添加",
                'error_code' => 20002
            ]);
        }
        $res = Product::create($params);
        return $res;
    }

    public function upProduct($params)
    {
        $product = Product::where("product_id",$params['product_id'])->findOrEmpty();
        if (!$product->isEmpty()){
            $res = Product::where("id", $product["id"])->update($params);
            if (!$res) {
                throw new intelligentliveException([
                    'msg' => "更新失败",
                    'error_code' => 20003
                ]);
            }
        } else {
            throw new intelligentliveException([
                'msg' => "商品不存在",
                'error_code' => 20003
            ]);
        }
        return true;
    }

    public function delProduct($params)
    {
        $info = Product::where("id",$params["id"])->findOrEmpty();
        if ($info->isEmpty()){
            throw new intelligentliveException([
                'msg' => '商品不存在',
                'error_code' => 20001
            ]);
        }
        $info->delete();
    }

    public function productList($params)
    {
        $pageSize = $params['pageSize']??200;
        $query = Product::field("*");
        if (!empty($params["product_name"])) {
            $query->where('product_name',"like","%".$params['product_name']."%");
        }
        $data = $query->paginate($pageSize);
        return $data;
    }
}